package com.wayz.serivce;

import com.wayz.constants.CAuditorType;
import com.wayz.constants.CUserStatus;
import com.wayz.entity.pojo.auditor.DAuditorUser;
import com.wayz.entity.redis.RLoginTokenMonitorUserIdValue;
import com.wayz.entity.vo.AuditorUserVO;
import com.wayz.entity.redis.RMonitorUserIdLoginTokenValue;
import com.wayz.exception.WayzException;
import com.wayz.entity.redis.RAuditor;
import com.wayz.mapper.DAuditorUserDAO;
import com.wayz.redis.RedisUtils;
import com.wayz.service.AuditorUserService;
import com.wayz.util.EncryptHelper;
import org.springframework.beans.BeanUtils;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;


/**
 * 审核方用户服务实现类
 *
 * @author mike.ma@wayz.ai
 */
@Service("auditorUserService")
@org.apache.dubbo.config.annotation.Service(version = "1.0.0", protocol = "dubbo")
@RefreshScope
public class AuditorUserServiceImpl implements AuditorUserService {

    /** Redis工具类 */
    @Resource(name = "redisUtils")
    private RedisUtils redisUtils;
	
	/** 值相关 */
	/** 登录令牌客户标识值 */
	@Resource(name = "rLoginTokenMonitorUserIdValue")
	private RLoginTokenMonitorUserIdValue rLoginTokenMonitorUserIdValue = null;
	/** 客户标识登录令牌值 */
	@Resource(name = "rMonitorUserIdLoginTokenValue")
	private RMonitorUserIdLoginTokenValue rMonitorUserIdLoginTokenValue = null;
	
    /** 审核方用户 */
    @Resource(name = "dAuditorUserDAO")
    private DAuditorUserDAO dAuditorUserDAO;

    /**
     * 创建审核方用户
     * @param myId
     * @param dto
     * @return
     * @throws WayzException
     */
    @Override
    public Long createUser(Long myId, DAuditorUser dto) throws WayzException {
        // 校验用户名是否存在 手机号
        Boolean exist = dAuditorUserDAO.existByPhone(dto.getTelephone());
        if (exist){
            throw new WayzException("审核方用户手机号已存在");
        }
		DAuditorUser create = new DAuditorUser();
		BeanUtils.copyProperties(dto, create);
        dAuditorUserDAO.create(create);
        return create.getId();
    }

	/**
     * 审核方重置密码
     * @param username  审核方用户名
     * @param newPassword  新的密码
     * @throws WayzException
     */
    @Override
    public void resetUserPassword(String username, String newPassword) throws WayzException {
    	AuditorUserVO vo = dAuditorUserDAO.getByUsernameOrPhone(username);
        if (vo == null){
            throw new WayzException("审核方用户不存在");
        }
        dAuditorUserDAO.updatePassword(vo.getId(), newPassword);
    }
    
    /**
     * 修改密码
     * @param myId 我的ID
     * @param oldPassword 原始密码
     * @param newPassword 新的密码
     */
    @Override
    public void modifyPassword(Long myId, String oldPassword, String newPassword) throws WayzException {
		// 检查用户
    	AuditorUserVO vo = dAuditorUserDAO.get(myId);
		if (vo == null) {
			throw new WayzException("审核方用户不存在");
		}
		if (oldPassword == null || !oldPassword.equalsIgnoreCase(vo.getPassword())) {
			throw new WayzException("原始密码错误");
		}
		dAuditorUserDAO.updatePassword(vo.getId(), newPassword);
    }
    
	/**
	 * 获取code
	 * 
	 * @param token 登录令牌
	 * @return code
	 * @throws WayzException 平台异常
	 */
	@Override
	public Long getMyId(String token) throws WayzException {
		// 初始化
		Long myId = rLoginTokenMonitorUserIdValue.get(token);

		// 返回数据
		return myId;
	}
	
	/**
	 * 获取当前用户公司标志
	 * 
	 * @param myId 我的用户标志
	 * @return 公司标志
	 */
	@Override
	public Long getCompanyId(Long myId) {
		Long companyId = null;
		AuditorUserVO vo = dAuditorUserDAO.get(myId);
		if (vo != null) {
			companyId = vo.getAuditorId();
		}
		return companyId;
	}
	
	/**
	 * 登录
	 * 
	 * @param username 客户电话
	 * @param password 客户密码
	 * @param ipAddress IP地址
	 * @return 用户信息
	 * @throws WayzException 平台异常
	 */
	@Override
	public AuditorUserVO login(String username, String password,String ipAddress) throws WayzException {
		// 获取用户信息
		AuditorUserVO vo = dAuditorUserDAO.getByUsernameOrPhone(username);
		if (vo != null) {
			// 验证用户权限
			// 验证用户权限: 用户被禁用
			if (CUserStatus.DISABLE.getValue() == vo.getStatus()) {
				throw new WayzException("对不起!您已被系统禁用,请联系管理员处理");
			}
			// 验证用户权限: 用户被删除
			// if (Boolean.TRUE.equals(dUser.getIsDeleted())) {
			// throw new WayzException("对不起!您已被系统删除,请联系管理员处理");
			// }
			// 验证用户权限: 用户密码错误
			if (password != null && !vo.getPassword().equals(password)) {
				throw new WayzException("用户密码错误");
			}
		}
		else {
			throw new WayzException("用户名和密码错误");
		}
		// 处理用户令牌
		// 处理用户令牌: 删除原有令牌
		Long userId = vo.getId();
		String oldToken = rMonitorUserIdLoginTokenValue.get(userId);
		if (oldToken != null) {
			rLoginTokenMonitorUserIdValue.remove(oldToken);
		}
		rMonitorUserIdLoginTokenValue.remove(userId);

		// 处理用户令牌: 添加新的令牌
		String loginToken = EncryptHelper.toMD5(username + System.currentTimeMillis());
		rLoginTokenMonitorUserIdValue.set(loginToken, userId);
		rMonitorUserIdLoginTokenValue.set(userId, loginToken);

		// 修改用户
		DAuditorUser modify = new DAuditorUser();
		modify.setId(userId);
		modify.setLoginToken(loginToken);
		dAuditorUserDAO.modify(modify);

		// 返回数据
		return getAuditor(userId);
	}
	
	private AuditorUserVO getAuditor(Long id){
		AuditorUserVO vo = dAuditorUserDAO.get(id);
		Short auditorType = Short.parseShort(redisUtils.hGet(RAuditor.getKey(id), RAuditor.TYPE).toString());
		vo.setAuditorType(auditorType);
		vo.setAuditorTypeName(CAuditorType.getDescription(auditorType));
		vo.setAuditorName(redisUtils.hGet(RAuditor.getKey(id), RAuditor.NAME).toString());
		return vo;
	}
	
	/**
	 * 登出
	 *
	 * @param myId
	 * @param token 登录令牌
	 * @throws WayzException 平台异常
	 */
	@Override
	public void logout(Long myId, String token) throws WayzException {
		// 删除映射
		// 删除映射: 登录令牌
		rLoginTokenMonitorUserIdValue.remove(token);
		rMonitorUserIdLoginTokenValue.remove(myId);
	}
}
